<template>
  <div class="category-manage">
    <el-container>
      <el-main>
        <div class="page-header">
          <h1>分类管理</h1>
        </div>

        <el-card>
          <div class="toolbar">
            <el-input
              v-model="keyword"
              placeholder="搜索分类名称"
              style="max-width: 260px"
              clearable
            />
            <el-button type="primary" @click="filterCategories">搜索</el-button>
            <el-button type="primary" @click="openAdd">新增分类</el-button>
            <el-button :disabled="!selected.length" @click="batchEnable">批量启用</el-button>
            <el-button :disabled="!selected.length" @click="batchDisable">批量禁用</el-button>
            <el-button type="danger" :disabled="!selected.length" @click="batchDelete"
              >批量删除</el-button
            >
          </div>
          <el-table
            :data="paginatedCategories"
            v-loading="loading"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="ID" prop="typeId" width="90" />
            <el-table-column label="分类名称" prop="typeName" />
            <el-table-column label="状态" width="120">
              <template #default="{ row }">
                <el-tag :type="row.status === '1' ? 'success' : 'info'">{{
                  row.status === '1' ? '启用' : '禁用'
                }}</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="180">
              <template #default="{ row }">
                <el-button size="small" @click="openEdit(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCategory(row.typeId)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
          <div class="pager">
            <el-pagination
              background
              layout="total, sizes, prev, pager, next, jumper"
              :page-size="pageSize"
              :current-page="page"
              :total="total"
              :page-sizes="[10, 20, 50, 100]"
              @current-change="handlePageChange"
              @size-change="handleSizeChange"
            />
          </div>
        </el-card>
      </el-main>
    </el-container>

    <!-- 新增/编辑分类对话框 -->
    <el-dialog
      :title="editing ? '编辑分类' : '新增分类'"
      v-model="dialogVisible"
      width="500px"
      @close="closeDialog"
    >
      <el-form :model="form" label-width="80px">
        <el-form-item label="分类名称" required>
          <el-input v-model="form.typeName" placeholder="请输入分类名称" />
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="form.status" placeholder="请选择状态">
            <el-option label="启用" value="1" />
            <el-option label="禁用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="closeDialog">取消</el-button>
          <el-button type="primary" @click="submit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { productService } from '@/api'
import type { Types } from '@/types'

type TypeRow = { typeId: number; typeName: string; status: string }

const loading = ref(false)
const categories = ref<TypeRow[]>([])
const selected = ref<TypeRow[]>([])
const dialogVisible = ref(false)
const editing = ref(false)
const editingId = ref<number | null>(null)
const form = ref<Partial<TypeRow>>({ typeName: '', status: '1' })
// 分页相关状态
const page = ref(1)
const pageSize = ref(10)
const keyword = ref('')
const total = ref(0)

// 过滤后的分类列表
const paginatedCategories = computed(() => {
  return categories.value
})

const loadCategories = async () => {
  loading.value = true
  try {
    const res = await productService.getTypesListPage(page.value, pageSize.value, keyword.value || undefined, undefined)
    if (res.data.code === 200) {
      const data = res.data.data
      if (data) {
        categories.value = data.list || []
        total.value = data.total || 0
      }
    }
  } catch (error) {
    console.error('获取分类列表失败:', error)
  } finally {
    loading.value = false
  }
}

const openAdd = () => {
  editing.value = false
  editingId.value = null
  form.value = { typeName: '', status: '1' }
  dialogVisible.value = true
}

const openEdit = async (category: TypeRow) => {
  editing.value = true
  editingId.value = category.typeId
  form.value = { typeName: category.typeName, status: category.status }
  dialogVisible.value = true
}

const closeDialog = () => {
  dialogVisible.value = false
}

const submit = async () => {
  if (!form.value.typeName?.trim()) {
    ElMessage.error('请输入分类名称')
    return
  }

  try {
    if (editing.value && editingId.value) {
      await productService.updateType(editingId.value, form.value as Partial<Types>)
      ElMessage.success('更新分类成功')
    } else {
      await productService.addType(form.value as Partial<Types>)
      ElMessage.success('新增分类成功')
    }
    dialogVisible.value = false
    await loadCategories()
  } catch (error) {
    ElMessage.error('操作失败，请重试')
    console.error('提交分类失败:', error)
  }
}

const deleteCategory = async (id: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这个分类吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    await productService.deleteType(id)
    ElMessage.success('删除分类成功')
    await loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('删除分类失败')
      console.error('删除分类失败', error)
    }
  }
}

const handleSelectionChange = (rows: TypeRow[]) => {
  selected.value = rows
}

const batchEnable = async () => {
  if (!selected.value.length) return

  try {
    await Promise.all(
      selected.value.map((item) =>
        productService.updateType(item.typeId, {
          typeName: item.typeName,
          status: '1',
        } as Partial<Types>),
      ),
    )
    ElMessage.success(`成功启用 ${selected.value.length} 个分类`)
    selected.value = []
    await loadCategories()
  } catch (error) {
    ElMessage.error('批量启用失败')
    console.error('批量启用失败', error)
  }
}

const batchDisable = async () => {
  if (!selected.value.length) return

  try {
    await Promise.all(
      selected.value.map((item) =>
        productService.updateType(item.typeId, {
          typeName: item.typeName,
          status: '0',
        } as Partial<Types>),
      ),
    )
    ElMessage.success(`成功禁用 ${selected.value.length} 个分类`)
    selected.value = []
    await loadCategories()
  } catch (error) {
    ElMessage.error('批量禁用失败')
    console.error('批量禁用失败', error)
  }
}

const batchDelete = async () => {
  if (!selected.value.length) return

  try {
    await ElMessageBox.confirm(
      `确定要删除选中的 ${selected.value.length} 个分类吗？`,
      '确认批量删除',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      },
    )

    await Promise.all(selected.value.map((item) => productService.deleteType(item.typeId)))
    ElMessage.success(`成功删除 ${selected.value.length} 个分类`)
    selected.value = []
    await loadCategories()
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error('批量删除失败')
      console.error('批量删除失败', error)
    }
  }
}

// 分页处理函数
const handlePageChange = (p: number) => {
  page.value = p
  loadCategories()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  page.value = 1 // 切换每页数量时重置到第一页
  loadCategories()
}

// 过滤分类
const filterCategories = () => {
  page.value = 1 // 搜索时重置到第一页
  loadCategories()
}

onMounted(() => {
  loadCategories()
})
</script>

<style scoped>
.category-manage {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
}
.toolbar {
  margin-bottom: 12px;
  display: flex;
  gap: 10px;
}

.pager {
  display: flex;
  justify-content: flex-end;
  margin-top: 12px;
}
</style>
